package com.zeus.base.smscenter.controller;

import com.zeus.base.privilege.model.TbCompany;
import com.zeus.base.privilege.model.TbUser;
import com.zeus.base.privilege.service.ICompanyService;
import com.zeus.base.privilege.utils.IdWorkerTools;
import com.zeus.base.privilege.utils.ResultModel;
import com.zeus.base.privilege.utils.StringUtil;
import com.zeus.base.smscenter.common.BaseController;
import com.zeus.base.smscenter.model.SmsSupplier;
import com.zeus.base.smscenter.model.SmsSupplierProperty;
import com.zeus.base.smscenter.model.Tenant;
import com.zeus.base.smscenter.service.ISmsSettingService;
import com.zeus.base.smscenter.service.ISupplierPropertyService;
import com.zeus.base.smscenter.service.ISupplierService;
import com.zeus.base.smscenter.utils.SessionUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 租户信息设定Controller
 */
@SuppressWarnings("ALL")
@RestController
@RequestMapping("/controller/smsSetting")
public class SmsSettingController extends BaseController {
    @Autowired
    private ISupplierService iSupplierService;
    @Autowired
    private ISmsSettingService iSmsSettingService;

    @Autowired
    private ISupplierPropertyService iSupplierPropertyService;


    @Autowired
    private ICompanyService iCompanyService;

    /**
     * 获取应用系统(默认参数,Add页面调用)
     *
     * @param keyId
     * @return
     */
    @RequestMapping(value = "/default", method = RequestMethod.POST)
    @ResponseBody
    public Tenant getAddDefaultTenant(HttpServletRequest request){

        return null;
    }

    /**
     * 获取租户Code
     * @param request
     * @return
     */
    @RequestMapping(value = "/getTenantCode", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<ResultModel> getTenantCode(HttpServletRequest request){

        TbUser loginUser = SessionUtil.getSessionUser(request);
        String companyCode = loginUser.getCompanyCodes();
        String companyCodes[] = companyCode.split(",");
        String rtnCode = "";
        StringBuffer sb = new StringBuffer();
        if(companyCodes.length > 0){
            for(int i=0;i<companyCodes.length;i++){
                sb.append("'");
                sb.append(companyCodes[i]);
                sb.append("'");
                sb.append(",");
            }
        }
        if(sb.length()>0){
            rtnCode = sb.toString();
            rtnCode = rtnCode.substring(0,rtnCode.length()-1);
        }
        ResponseEntity<ResultModel> resultModel = new ResponseEntity<ResultModel>(new ResultModel(true,rtnCode), HttpStatus.OK);
        return resultModel;
    }

    /**
     * 获取租户Code
     * @param request
     * @return
     */
    @RequestMapping(value = "/getTenantCodeForSelectBox", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<ResultModel> getTenantCodeForSelectBox(HttpServletRequest request){

        TbUser loginUser = SessionUtil.getSessionUser(request);

        ResponseEntity<ResultModel> resultModel = new ResponseEntity<ResultModel>(new ResultModel(true,loginUser.getCompanyCodes()), HttpStatus.OK);
        return resultModel;
    }

    /**
     * 获取租户信息
     *
     * @param keyId
     * @return
     */
    @RequestMapping(value = "/get", method = RequestMethod.POST)
    @ResponseBody
    public Tenant getTenant(String keyId,HttpServletRequest request){

        Tenant tenant = iSmsSettingService.selectByPrimaryKey(keyId);

        return tenant;
    }

    /**
     * 添加保存
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("SmsCenterTenantManager:add")
    public ResponseEntity<ResultModel> save(Tenant tenant, HttpServletRequest request) {
        if (tenant != null) {
            if(StringUtil.isEmpty(tenant.getId())){
                tenant.setId(IdWorkerTools.getInstance().getId().toString());
            }
            tenant.setCreateTime(new Date());
            //添加之前,先验证用户输入的租户唯一标识是否正确
            if(StringUtil.isNotEmpty(getTenantCodeMap(request).get(tenant.getCode()))){
                //如果输入的是正确的,那再进行数据是否存在的验证,如果已经存在,则不能再次添加.
                Tenant tenantOld = iSmsSettingService.selectByCode(tenant.getCode());
                if(tenantOld!=null && StringUtils.isNotEmpty(tenantOld.getId())){
                    ResultModel resultModel = new ResultModel(false);
                    resultModel.setMessage("该租户信息已经存在,请勿重复添加!");
                    resultModel.setSuccess(false);
                    return new ResponseEntity<ResultModel>(resultModel, HttpStatus.OK);
                }
                TbCompany tbCompany = iCompanyService.queryByCompanyCode(tenant.getCode());
                tenant.setName(tbCompany.getCompanyName());
                if(tbCompany.getParent()!=null){
                    tenant.setHeadCode(tbCompany.getParent().getCompanyCode());
                }else{
                    tenant.setHeadCode(tenant.getCode());
                }

                return new ResponseEntity<ResultModel>(iSmsSettingService.insert(tenant), HttpStatus.OK);
            }else{
                ResultModel resultModel = new ResultModel(false);
                resultModel.setMessage("租户唯一标识输入不正确,请输入正确的数据!");
                resultModel.setSuccess(false);
                return new ResponseEntity<ResultModel>(resultModel, HttpStatus.OK);
            }
        }
        return new ResponseEntity<ResultModel>(new ResultModel(false), HttpStatus.OK);
    }

    /**
     * 修改保存
     *
     * @param company
     * @param request
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("SmsCenterTenantManager:update")
    public ResponseEntity<ResultModel> update(Tenant tenant, HttpServletRequest request) {
        if (tenant != null) {
            tenant.setUpdateTime(new Date());
            return new ResponseEntity<ResultModel>(iSmsSettingService.update(tenant), HttpStatus.OK);
        }
        return new ResponseEntity<ResultModel>(new ResultModel(false), HttpStatus.OK);
    }

    public Map<String,String> getTenantCodeMap(HttpServletRequest request){

        TbUser loginUser = SessionUtil.getSessionUser(request);
        String companyCode = loginUser.getCompanyCodes();
        String companyCodes[] = companyCode.split(",");
        Map<String,String> map = new HashMap<String,String>();
        if(companyCodes.length > 0){
            for(int i=0;i<companyCodes.length;i++){
                map.put(companyCodes[i],companyCodes[i]);
            }
        }
        return map;
    }

    /**
     * 删除
     *
     * @param keyId
     * @param request
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("SmsCenterTenantManager:delete")
    public ResponseEntity<ResultModel> delete(String keyId, HttpServletRequest request) {
        if (keyId != null && StringUtil.isNotEmpty(keyId)) {
            //删除前,先删除该租户下的所有供应商及供应商属性后,再删除租户信息
            //删除供应商属性
            SmsSupplierProperty smsSupplierPropertyCond = new SmsSupplierProperty();
            smsSupplierPropertyCond.setTenantCode(keyId);
            iSupplierPropertyService.deleteByCode(smsSupplierPropertyCond);
            //删除供应商
            SmsSupplier smsSupplier = new SmsSupplier();
            smsSupplier.setTenantCode(keyId);
            iSupplierService.deleteByTenantCode(smsSupplier);
            //删除租户
            return new ResponseEntity<ResultModel>(iSmsSettingService.deleteByCode(keyId), HttpStatus.OK);
        }
        return new ResponseEntity<ResultModel>(new ResultModel(false), HttpStatus.OK);
    }

    /**
     * 批量删除
     *
     * @param keyIds
     * @param request
     * @return
     */
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("SmsCenterTenantManager:delete")
    public ResponseEntity<ResultModel> batchDelete(String keyIds, HttpServletRequest request) {
        if (StringUtil.isNotEmpty(keyIds)) {
            return new ResponseEntity<ResultModel>(iSmsSettingService.batchDelete(keyIds.split(",")), HttpStatus.OK);
        }
        return new ResponseEntity<ResultModel>(new ResultModel(false), HttpStatus.OK);
    }
}
